import 'package:awak/common/models/user.dart';
import 'package:awak/common/db/db_helper.dart';

class UserRepository {
  static final UserRepository _instance = UserRepository._internal();
  factory UserRepository() => _instance;
  UserRepository._internal();

  User? currentUser;

  // 注册
  Future<int> register(User user) async {
    final db = await DBHelper.database;
    return await db.insert('user', user.toMap());
  }

  // 登录
  Future<User?> login(String username, String password) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'user',
      where: 'username = ? AND password = ?',
      whereArgs: [username, password],
    );
    if (res.isNotEmpty) {
      currentUser = User.fromMap(res.first);
      return currentUser;
    }
    return null;
  }

  // 退出登录
  Future<void> logout() async {
    currentUser = null;
  }

  // 删除用户
  Future<void> deleteUser() async {
    final db = await DBHelper.database;
    await db.delete('user', where: 'id = ?', whereArgs: [currentUser!.id]);
    currentUser = null;
  }

  // 根据用户名获取用户
  Future<User?> getUserByUsername(String username) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'user',
      where: 'username = ?',
      whereArgs: [username],
    );
    if (res.isNotEmpty) {
      return User.fromMap(res.first);
    }
    return null;
  }

  // 更新用户信息
  Future<int> update(User user) async {
    final db = await DBHelper.database;
    return await db.update(
      'user',
      user.toMap(),
      where: 'id = ?',
      whereArgs: [user.id],
    );
  }

  // 获取所有用户
  Future<List<User>> getAllUsers() async {
    final db = await DBHelper.database;
    final res = await db.query('user');
    return res.map((e) => User.fromMap(e)).toList();
  }

  // 根据ID获取用户
  Future<User?> getUserById(int id) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'user',
      where: 'id = ?',
      whereArgs: [id],
    );
    if (res.isNotEmpty) {
      return User.fromMap(res.first);
    }
    return null;
  }
}